package com.zxsj.fdk.study.common.exception;

import com.zxsj.fdk.study.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import static com.zxsj.fdk.study.common.Result.error;
import static com.zxsj.fdk.study.common.error.BaseErrorMessage.HTTP_METHOD_ERROR;
import static com.zxsj.fdk.study.common.error.BaseErrorMessage.ILLEGAL_PARAM;


/**
 * @Description 异常处理类
 * @Author mengweibin
 * @Date 2021-04-15 15:41
 */
@RestController
@ControllerAdvice
@Slf4j
public class ExceptionHandlerController {



    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result bindException(MethodArgumentNotValidException e) {

        String msg = "Parameter binding error";
        FieldError error = e.getBindingResult().getFieldError();
        if (error != null) {
            msg = error.getField() + error.getDefaultMessage();
        }
        log.warn(ILLEGAL_PARAM.getMsg(), e);
        return error(ILLEGAL_PARAM.getCode(), msg);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return error(HTTP_METHOD_ERROR);
    }

    /**
     * 请求参数缺失
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("参数不合法", e);
        return error(ILLEGAL_PARAM);
    }
}
